
const luckyScroll = {

  /**
   * 【滚动抽奖】获取页面呈现的奖品数据源
   *
   * @param configs { source, total, visibleCount }
   * @returns
   */
  getLuckyScrollDataList: (configs) => {
    // 获取配置数据
    const { source, total, visibleCount } = configs

    if (!source?.length) {
      return []
    }
    // 获取数据源
    const t = [...source]
    // 获取数据长度
    const len = source.length
    // 计算后置填充的数据条数
    const tail = Math.floor(visibleCount / 2)
    // 前置填充的数据条数
    while (t.length < total - tail) {
      const i = Math.floor(Math.random() * len)
      t.unshift(source[i])
    }
    // 后置填充的数据条数
    while (t.length < total) {
      const i = Math.floor(Math.random() * len)
      t.push(source[i])
    }
    return t
  },

  /**
   * 【滚动抽奖】开始滚动
   * @param options
   */
  startScroll: (options) => {
    const {
      itemWidth,
      wrap,
      completed,
      winningID,
      winningIDs,
      visibleItemCount,
      audioUriForStart,
      audioUriForEnd,
      duration = 5,
      openAnimation = true,
      openSound = true,
      isOne = false
    } = options
    // -- 每次触发动画之前先复位状态
    wrap.style.transition = `transform 0s ease 0s`
    wrap.style.transform = `translateX(0px)`
    // -- 满足条件：播放开始音效
    if (openSound && openAnimation && audioUriForStart) {
      luckyScroll.playAudio(audioUriForStart)
    }
    // 调用 requestAnimationFrame 在下一周期内开始抽奖动效
    requestAnimationFrame(() => {

      // 查询可视区的中间元素的索引
      const mIndex = Math.floor(visibleItemCount / 2)
      const slice = winningIDs.slice(0, winningIDs.length - mIndex)
      const index = slice.lastIndexOf(winningID)
      // -- 未找到中奖物品，终止程序
      if (index === -1) return
      // -- 动态计算偏移
      const offset = -(index - mIndex) * itemWidth
      // 动画完成时的回调函数
      const handleStop = () => {
        if (openSound && audioUriForEnd) {
          luckyScroll.playAudio(audioUriForEnd)
        }
        completed?.()
      }
      if (openAnimation) {
        wrap.style.transition = `transform ${duration}s cubic-bezier(0.35, 0.08, 0.26, 0.93) 0s`
        wrap.style.transform = `translateX(${offset}px)`
        // 当动画结束时，执行回调函数
        if (!isOne) {
          const timer = setTimeout(() => {
            clearTimeout(timer)
            handleStop()
          }, 3000)
          return
        }
        wrap.ontransitionend = function () {
          handleStop()
        }
        return
      }

      wrap.style.transform = `translateX(${offset}px)`
      handleStop()

    })

  },

  /**
   * 播放音效
   * @param uri 音效地址
   */
  playAudio: (uri) => {
    const audio = new Audio(uri)
    audio.play()
    audio.onended = function () {
      audio.src = ''
      audio.srcObject = null
      audio.remove()
    }
  }

}

export default luckyScroll